﻿using System.Drawing;
using System.Web;

namespace WebImageResizer.Filters
{
	internal class ResizeFilter : IImageFilter
	{
		#region IImageFilter Members

		public bool Process(HttpContext context, ref Bitmap bitmap)
		{
			string widthParameter = context.Request["width"];
			string heightParameter = context.Request["height"];

			if (!string.IsNullOrEmpty(widthParameter) || !string.IsNullOrEmpty(heightParameter))
			{
				int imageResizeWidth = 0;
				int imageResizeHeight = 0;

				// Preserve aspect only if either width or height is specified, not both.
				if (!string.IsNullOrEmpty(widthParameter))
				{
					int width;
					if (int.TryParse(widthParameter, out width))
					{
						imageResizeWidth = width;
					}
				}

				if (!string.IsNullOrEmpty(heightParameter))
				{
					int height;
					if (int.TryParse(heightParameter, out height))
					{
						imageResizeHeight = height;
					}
				}

				if (imageResizeWidth == 0 && imageResizeHeight == 0)
				{
					imageResizeWidth = bitmap.Width;
					imageResizeHeight = bitmap.Height;
				}

				IImageTool imageTool = Factory.GetImageTool();
				bitmap = imageTool.Resize(bitmap, imageResizeWidth, imageResizeHeight, true);
				return true;
			}

			return false;
		}

		#endregion
	}
}